package com.kuangstudy.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2023年09月15日
 * @Description
 */
@RestController
@Api(tags = "Lua脚本完成限流")
public class IpLuaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DefaultRedisScript<Long> ipLimitLua;


    @PostMapping("/userip/lua/limit")
    @ApiOperation("根据用户ip使用lua脚本限流")
    public String userIpToLuaLimiter(String userIp) {
        String limitKey = "user:ip:limit:" + userIp;
        List<String> stringList = Arrays.asList(limitKey);
        // 1s最多访问五次
        Long result = stringRedisTemplate.execute(ipLimitLua, stringList, "1", "3");
        if (result == 0) {
            return "客官,你慢点点击,我快要承受不住了...";
        }
        return "success";
    }

}
